<template>
    <div class="main">
        <el-card class="search-card">
            <div class="search-header">
                <h2>商品分类管理</h2>
                <div class="actions">
                    <el-button class="button" type="primary" :icon="Plus" @click="add">添加类别</el-button>
                    <el-button class="button" type="danger" :icon="Delete" @click="deleteRows">批量删除</el-button>
                    <el-button :icon="Refresh" @click="search">刷新</el-button>
                </div>
            </div>
        </el-card>

        <el-card class="data-card">
            <div class="data">
                <div class="grid">
                    <el-table 
                        :data="treeData" 
                        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
                        row-key="id" 
                        border 
                        style="width: 100%" 
                        :header-cell-style="{ textAlign: 'center', backgroundColor: '#f5f7fa' }"
                        :cell-style="{ textAlign: 'center' }" 
                        ref="tableRef"
                        v-loading="loading">
                        <el-table-column type="selection" width="55" :selectable="selectable" />
                        <el-table-column prop="id" label="编号" width="80" />
                        <el-table-column prop="name" label="类型名称" width="200">
                            <template #default="scope">
                                <span class="category-name">{{ scope.row.name }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="parentId" label="父类型" width="150">
                            <template #default="scope">
                                <el-tag v-if="scope.row.parentId === 0" type="success">根类别</el-tag>
                                <span v-else-if="scope.row.parentId === 28">所有类别</span>
                                <span v-else-if="scope.row.parentId === 1">手机数码</span>
                                <span v-else-if="scope.row.parentId === 2">服装</span>
                                <span v-else-if="scope.row.parentId === 3">家用电器</span>
                                <span v-else-if="scope.row.parentId === 4">电脑办公</span>
                                <span v-else-if="scope.row.parentId === 5">家具用品</span>
                                <span v-else>{{ getParentCategoryName(scope.row.parentId) }}</span>
                            </template>
                        </el-table-column>
<!--                        <el-table-column prop="isLook" label="是否显示" width="120">-->
<!--                            <template #default="scope">-->
<!--                                <el-switch -->
<!--                                    @change="updateLook(scope.row)" -->
<!--                                    v-model="scope.row.isLook" -->
<!--                                    active-text="显示"-->
<!--                                    inactive-text="隐藏"-->
<!--                                    inline-prompt-->
<!--                                />-->
<!--                            </template>-->
<!--                        </el-table-column>-->
                      <el-table-column prop="sort" label="排序号" width="200">
                        <template #default="scope">
                          <span class="category-sort">{{ scope.row.sort }}</span>
                        </template>
                      </el-table-column>
                        <el-table-column fixed="right" label="操作" min-width="200">
                            <template #default="scope">
                                <el-button type="danger" :icon="Delete" @click="deleteRow(scope.row)" size="small">删除</el-button>
                                <el-button type="primary" :icon="Edit" @click="editRow(scope.row)" size="small">编辑</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </el-card>

        <el-dialog 
            v-model="show" 
            :title="title" 
            width="600px" 
            draggable 
            :close-on-click-modal="false"
            :before-close="handleClose">
            <!-- 新增操作的表单 -->
            <el-form :model="cam" ref="sfRef" label-width="100px">
                <el-form-item label="类别名称" prop="name" :rules="[{ required: true, message: '请输入类别名称', trigger: 'blur' }]">
                    <el-input placeholder="请输入类别名称" v-model="cam.name" />
                </el-form-item>
                <el-form-item label="父类别" prop="parentId">
                    <el-cascader 
                        placeholder="请选择父类别" 
                        v-model="cam.parentId" 
                        :options="camTreeData"
                        :render-after-expand="false" 
                        :props="props1" 
                        clearable 
                        style="width: 100%"
                    />
                </el-form-item>
<!--                <el-form-item label="是否显示" prop="isLook">-->
<!--                    <el-switch -->
<!--                        v-model="cam.isLook" -->
<!--                        active-text="显示" -->
<!--                        inactive-text="隐藏"-->
<!--                        :active-value="1"-->
<!--                        :inactive-value="0"-->
<!--                    />-->
<!--                </el-form-item>-->
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleClose">取消</el-button>
                    <el-button type="primary" @click="submitForm">确认</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { Plus, Edit, Search, Refresh, Delete, CircleClose, CircleCheck } from '@element-plus/icons-vue'
import { ref, onMounted, toRaw, nextTick } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { findTree, deleteByIds, updateIsLook, save, update as updateCategory } from '@/api/ItemCategoryApi';

const loading = ref(false);

onMounted(() => {
    search();
})

// 添加selectable函数定义
function selectable(row, index) {
    // 默认所有行都可选择
    return true;
}

const treeData = ref([]);

async function search() {
    loading.value = true;
    try {
        let resp = await findTree();
        console.log("API Response:", resp);
        // 修复数据处理逻辑，正确处理findTree API返回的数据结构
        // findTree API直接返回data数组，而不是{code, data, message}对象
        if (Array.isArray(resp) && resp.length > 0) {
            // 先设置原始数据
            treeData.value = resp;
            
            // 然后处理数据，转换isLook字段
            treeData.value = treeData.value.map(item => {
                // 处理根节点
                const processedItem = {
                    ...item,
                    isLook: item.isLook === 1
                };
                
                // 处理子节点
                if (item.children && Array.isArray(item.children)) {
                    processedItem.children = item.children.map(child => {
                        return {
                            ...child,
                            isLook: child.isLook === 1
                        };
                    });
                }
                
                return processedItem;
            });
            
            console.log("Processed treeData:", treeData.value);
        } else {
            console.log("No data received or invalid response structure");
            treeData.value = [];
        }
    } catch (error) {
        ElMessage.error("获取数据失败: " + error.message);
        treeData.value = [];
    } finally {
        loading.value = false;
    }
}

function getParentCategoryName(parentId) {
    // 根据parentId查找父类别的名称
    for (let category of treeData.value) {
        if (category.id === parentId) {
            return category.name;
        }
        if (category.children) {
            for (let child of category.children) {
                if (child.id === parentId) {
                    return child.name;
                }
            }
        }
    }
    return '顶级分类';
}

function deleteRow(row) {
    const ids = [row.id];
    deleteCategory(ids);
}

async function updateLook(row) {
    console.log(row.isLook);
    try {
        let resp;
        if (row.isLook === false) {
            resp = await updateIsLook(row.id, 0);
        } else {
            resp = await updateIsLook(row.id, 1);
        }
        
        if (resp.code == 200) {
            ElMessage.success(row.isLook ? "显示成功" : "取消显示");
        } else {
            ElMessage.error(resp.msg || "操作失败");
            // 恢复开关状态
            row.isLook = !row.isLook;
        }
    } catch (error) {
        ElMessage.error("操作失败: " + error.message);
        // 恢复开关状态
        row.isLook = !row.isLook;
    }
}

async function deleteCategory(ids) {
    ElMessageBox.confirm("是否确认删除所选行? 删除后无法恢复！", "警告", {
        type: "warning",
        confirmButtonText: "确认删除",
        cancelButtonText: "取消"
    })
        .then(async () => {
            try {
                let resp = await deleteByIds(ids);
                if (resp.code == 200) {
                    ElMessage.success("删除成功");
                    search();
                } else {
                    ElMessage.error(resp.msg || "删除失败，网络异常");
                }
            } catch (error) {
                ElMessage.error("删除失败: " + error.message);
            }
        })
        .catch(() => { 
            // 用户取消删除
        });
}

let tableRef;
function deleteRows() {
    let rows = tableRef.getSelectionRows();
    console.log(rows);
    let ids = [];
    for (let row of rows) {
        ids.push(toRaw(row).id);
    }
    if (ids.length === 0) {
        ElMessage.warning("请至少选择一项");
        return;
    }
    deleteAllRows(ids);
}

async function deleteAllRows(ids) {
    ElMessageBox.confirm(`是否确认删除这 ${ids.length} 项? 删除后无法恢复！`, "批量删除确认", {
        type: "warning",
        confirmButtonText: "确认删除",
        cancelButtonText: "取消"
    })
        .then(async () => {
            try {
                let resp = await deleteByIds(ids);
                if (resp.code == 200) {
                    ElMessage.success("删除成功");
                    search();
                } else {
                    ElMessage.error(resp.msg || "删除失败");
                }
            } catch (error) {
                ElMessage.error("删除失败: " + error.message);
            }
        })
        .catch(() => { 
            // 用户取消删除
        });
}

const show = ref(false);
const title = ref("新增类别");
const cam = ref({
    name: "",
    parentId: "",
    isLook: 1,
});

let camTreeData = ref();

function handleClose() {
    show.value = false;
    // 重置表单
    cam.value = {
        name: "",
        parentId: "",
        isLook: 1,
    };
}

async function add() {
    show.value = true;
    title.value = "新增类别";
    cam.value = { // 重置表单数据
        name: "",
        parentId: "",
        isLook: 1,
    };

    await findAllCategory();
}

async function findAllCategory() {
    try {
        //查询下拉树
        let resp = await findTree();
        console.log("Cascader API Response:", resp);
        // 修复数据处理逻辑，正确处理findTree API返回的数据结构
        // findTree API直接返回data数组，而不是{code, data, message}对象
        if (Array.isArray(resp) && resp.length > 0) {
            let tree = resp;
            console.log("Cascader tree data:", tree);
            buildTree(tree);
            camTreeData.value = tree;
        } else {
            camTreeData.value = [];
        }
    } catch (error) {
        ElMessage.error("获取分类数据失败: " + error.message);
        camTreeData.value = [];
    }
}

function buildTree(noArray) {
    for (let node of noArray) {
        node.label = node.name;
        node.value = node.id;
        if (Array.isArray(node.children)) {
            buildTree(node.children);
        }
    }
}

const props1 = {
    checkStrictly: true,
}

function handleSelect(value) {
    // 确保 value 存在且是一个对象，并且 parentId 是一个数组
    if (!value || typeof value !== 'object' || !Array.isArray(value.parentId) || value.parentId.length === 0) {
        console.error("handleSelect函数接收到的值无效:", value);
        return;
    }
    let selectedId = value.parentId[value.parentId.length - 1];

    return selectedId;
}

function submitForm() {
    let selectedValue = toRaw(cam.value);  // 获取树状选择的当前值
    let parentId = handleSelect(selectedValue);  // 调用 handleSelect 并传递对象

    let cdm = toRaw(cam.value);

    // 将选中的分类ID赋值给parentId
    cdm.parentId = parentId;
    console.log("提交的数据:", cdm);

    if (!cdm.name) {
        ElMessage.warning("请输入类别名称");
        return;
    }

    if (cdm.id) {
        update(cdm);
    } else {
        addCategory(cdm);
    }
}

async function addCategory(cdm) {
    try {
        let resp = await save(cdm);
        console.log(resp.data);
        if (resp.code == 200) {
            ElMessage.success("添加成功");
            search();
            show.value = false;
        } else {
            ElMessage.error(resp.msg || "添加失败");
        }
    } catch (error) {
        ElMessage.error("添加失败: " + error.message);
    }
}

function editRow(row) {
    findAllCategory();
    row = Object.assign({}, row);
    show.value = true;
    title.value = "编辑类别";
    // 转换isLook值以匹配表单
    row.isLook = row.isLook ? 1 : 0;
    nextTick(() => {
        cam.value = row;
    });
}

async function update(cdm) {
    try {
        let resp = await updateCategory(cdm);
        if (resp.code == 200) {
            ElMessage.success("修改成功");
            search();
            show.value = false;
        } else {
            ElMessage.error(resp.msg || "修改失败");
        }
    } catch (error) {
        ElMessage.error("修改失败: " + error.message);
    }
}
</script>

<style scoped>
.main {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: calc(100vh - 40px);
}

.search-card {
    margin-bottom: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 15px;
}

.search-header h2 {
    margin: 0;
    color: #303133;
    font-size: 20px;
    font-weight: 600;
}

.actions {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

.data-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.data {
    margin-top: 20px;
}

.category-name {
    font-weight: 500;
    color: #606266;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    padding: 0 20px 20px;
}

:deep(.el-dialog__header) {
    border-bottom: 1px solid #eee;
    margin-right: 0 !important;
}

:deep(.el-table__row .cell) {
    padding: 5px 0;
}

@media (max-width: 768px) {
    .main {
        padding: 10px;
    }
    
    .search-header {
        flex-direction: column;
        align-items: stretch;
    }
    
    .actions {
        justify-content: center;
    }
    
    .el-card {
        margin-bottom: 15px;
    }
}
</style>